package demo.view;

import java.awt.Component;
import java.util.Arrays;
import java.util.Comparator;

import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.event.ListSelectionListener;

import demo.controler.AddressBookControler;
import demo.model.AddressBook;
import demo.model.Contact;
import demo.model.ContactObserver;

public class ContactList extends JList<Contact> implements ContactObserver {

	private static final long serialVersionUID = 1L;
	private Contact[] currentContacts;
	private Comparator<Contact> comparator;
	final private AddressBookControler bookControler;

	public ContactList(AddressBookControler ctrl) {
		comparator = Contact.getNaturalComparator();
		setCellRenderer(new ContactCellRenderer());
		ctrl.addObserver(this);
		bookControler = ctrl;
		refresh();
	}

	public void addSelectionListener(ListSelectionListener lst) {
		getSelectionModel().addListSelectionListener(lst);
	}

	@Override
	public void updateContact(Contact contact, AddressBook addressBook) {
		refresh();
	}

	private void refresh() {
		currentContacts = bookControler.getContacts();
		Arrays.sort(currentContacts, comparator);
		setListData(currentContacts);
	}

	class ContactCellRenderer extends JLabel implements
			ListCellRenderer<Contact> {
		private static final long serialVersionUID = 1L;

		@Override
		public Component getListCellRendererComponent(
				JList<? extends Contact> list, Contact contact, int index,
				boolean isSelected, boolean cellHasFocus) {
			String s = contact.getLastName() + ", " + contact.getFirstName();
			setText(s);
			setEnabled(list.isEnabled());
			setFont(list.getFont());
			setOpaque(true);
			return this;
		}
	}
}
